﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Common;
using System.Threading;

namespace 浏览器
{
    //Windows进程间通信—命名管道
    //http://www.cnblogs.com/roucheng/p/windowsguandao.html
    public partial class FrmBrowser : Form
    {
        public FrmBrowser()
        {
            InitializeComponent();
        }

        private void FrmBrowser_Load(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(Rec));
            th.IsBackground = true;
            th.Start();
        }

        #region 服务端接收
        public void Rec()
        {
            while (true)
            {
                IntPtr pipeHandle = NamedPipeLib.CreateNamedPipe(
                             @"\\.\pipe\PMYBrowser",
                             NamedPipeLib.PIPE_ACCESS_DUPLEX,
                             NamedPipeLib.PIPE_TYPE_MESSAGE | NamedPipeLib.PIPE_READMODE_MESSAGE,
                             NamedPipeLib.PIPE_UNLIMITED_INSTANCES,
                             1024,
                             1024,
                             0,
                             IntPtr.Zero);

                uint u = NamedPipeLib.GetLastError();

                if (pipeHandle.ToInt32() == NamedPipeLib.INVALID_HANDLE_VALUE)
                {
                    MessageBox.Show("创建管道出错");
                    return;
                }

                bool connected = NamedPipeLib.ConnectNamedPipe(pipeHandle, null) ? true : (NamedPipeLib.GetLastError() == NamedPipeLib.ERROR_PIPE_CONNECTED);

                if (connected)
                {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(ReadMessage), pipeHandle);
                }
                else
                {
                    NamedPipeLib.CloseHandle(pipeHandle);
                }
            }
        }

        public static void ReadMessage(object arg)
        {
            IntPtr pipeHandle = (IntPtr)arg;

            byte[] numReadWritten = new byte[4];
            byte[] intBytes = new byte[4];

            NamedPipeLib.ReadFile(pipeHandle, intBytes, 4, numReadWritten, 0);

            int len = BitConverter.ToInt32(intBytes, 0);

            byte[] recBuffer = new byte[len];

            NamedPipeLib.ReadFile(pipeHandle, recBuffer, (uint)len, numReadWritten, 0);

            //string str = Encoding.UTF8.GetString(recBuffer);
            ShareMessage msg = BytesConvert.BytesToObject<ShareMessage>(recBuffer);
            string str = msg.MsgContent;

            MessageBox.Show(str, "浏览器收到");

            NamedPipeLib.FlushFileBuffers(pipeHandle);

            NamedPipeLib.DisconnectNamedPipe(pipeHandle);

            NamedPipeLib.CloseHandle(pipeHandle);
        }

        #endregion

        public void SendMsg()
        {
            string pipeName = @"\\.\pipe\PMYMain";

            string msg = textBox1.Text;

            byte[] msgBuffer = Encoding.UTF8.GetBytes(msg);

            IntPtr fileHandle;

            while (true)
            {

                fileHandle = NamedPipeLib.CreateFile(pipeName,
                    NamedPipeLib.GENERIC_READ | NamedPipeLib.GENERIC_WRITE,
                    0, null, NamedPipeLib.OPEN_EXISTING, 0, 0);


                if (fileHandle.ToInt32() != NamedPipeLib.INVALID_HANDLE_VALUE)
                    break;

                if (NamedPipeLib.GetLastError() != NamedPipeLib.ERROR_PIPE_BUSY)
                {
                    MessageBox.Show("不能打开管道");
                    return;
                }

                if (!NamedPipeLib.WaitNamedPipe(pipeName, 20000))
                {
                    Console.WriteLine("不能打开管道");
                    return;
                }
            }

            uint pipeMode = NamedPipeLib.PIPE_READMODE_MESSAGE;

            bool success = NamedPipeLib.SetNamedPipeHandleState(fileHandle, ref pipeMode, IntPtr.Zero, IntPtr.Zero);



            if (!success)
            {
                Console.WriteLine("设置管道状态失败");
                return;
            }

            uint len = (uint)msgBuffer.Length;

            byte[] numReadWritten = new byte[4];

            success = NamedPipeLib.WriteFile(fileHandle, BitConverter.GetBytes(len), 4, numReadWritten, 0);

            if (!success)
            {
                Console.WriteLine("写入数据失败");
                return;
            }
            else
            {
                NamedPipeLib.WriteFile(fileHandle, msgBuffer, len, numReadWritten, 0);
            }

            NamedPipeLib.CloseHandle(fileHandle);

        }

        private void button1_Click(object sender, EventArgs e)
        {
            ShareMessage msg = new ShareMessage();
            msg.MsgContent = textBox1.Text;
            NamedPipeLib.SendMsg(msg, false);
        }
    }
}
